<template>
  <div>
    <!-- 图表数据配置 -->
    <div style="margin-top: 16px;">
      <el-form v-if="isChart" ref="moduleNameForm" :model="dataForm" :rules="formRules" label-position="right" label-width="80px">
        <el-form-item label="模块名称" prop="name" class="name" style="margin-right: 20px;">
          <el-input
            v-model.trim="dataForm.name"
            maxlength="20"
            class="width240"
            size="small"
            placeholder="请填写模块名称"
            name="name"
            type="text"/>
        </el-form-item>
      </el-form>
      <Title id="data" title="数据配置" style="margin-bottom: 16px;"/>
      <SelectLabel ref="SelectLabel" :is-contrast="true" :remove-duplicate="true" show-extend @tabNameChange="tabNameChange" @tagDelete="tagDelete" />
      <el-form ref="formDataRef" :model="dataForm" label-position="right" class="lineHeight32" label-width="80px">
        <el-form-item label="定时更新" prop="isUpdateRegularly" class="isUpdateRegularly">
          <div style="height: 30px;">
            <el-switch v-model="dataForm.isUpdateRegularly" class="fb-switch"/>
            <el-select
              v-if="dataForm.isUpdateRegularly"
              v-model="dataForm.updateRegularlyType"
              placeholder="请选择"
              size="small"
              class="select-updateRegularlyType"
              popper-class="global-select-down"
              name="sortType">
              <el-option
                v-for="item in updateRegularlyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item v-if="dataForm.moduleType === TAG_MODULE_STYLE.HISTOGRAM_MODULE" label="排序" prop="isOrder" class="isUpdateRegularly">
          <div class="flex-center" style="height: 30px;">
            <el-switch v-model="dataForm.isOrder" class="fb-switch" />
            <div v-if="dataForm.isOrder" class="select-sort">
              <el-select
                v-model="dataForm.sortType"
                placeholder="排序"
                size="small"
                popper-class="global-select-down"
                name="sortType">
                <el-option
                  v-for="item in sortOpt"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 选择图表样式 -->
    <ChartStyle id="style" ref="chartStyleRef" v-model="dataForm" @getTagNames="getTagNames"/>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" @click="toSubmit">保存</el-button>
        <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose">取消</el-button>
      </div>
      <div v-if="isEdit" class="foot-info">
        <div class="item">更新人：{{ dataForm.updateUserName || '--' }}</div>
        <div class="item">
          更新时间：
          <span v-if="dataForm.updateTime">{{ dataForm.updateTime | format('YYYY/MM/DD HH:mm') }}</span>
          <span v-else>--</span>
        </div>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import Title from '@/components/Title';
import ChartStyle from './chartStyle';
import SelectLabel from './selectLabel';
import { createChartTable, editChartTable } from '@/api/reportManage';
import { parseJson } from '@/utils';
import { updateRegularlyOptions } from '@/components/ReportManage/chartCreate/module/selectData.js';
import { TAG_MODULE_STYLE } from '@/utils/const/echarts';
import { generateUUID } from '@/utils/tools';
import { format } from '@/filters/date';

export default {
  components: { ChartStyle, SelectLabel, Title },
  filters: { format },
  props: {
    process: {
      type: Number,
      default: 0
    },
    tabId: {
      type: String | Number,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      TAG_MODULE_STYLE,
      btnLoading: false,
      updateRegularlyOptions,
      sortOpt: [{ id: 1, name: '正序' }, { id: 2, name: '倒序' }],
      dataForm: {
        // ChartStyle
        name: '',
        layout: '',
        layoutNum: 36,
        moduleType: 0,
        tags: [{
          uuid: generateUUID(),
          unit: '',
          tagType: 0,
          hideTag: 0,
          tagName: '',
          reportId: '',
          fieldId: '',
          filedFormula: '',
          fieldCategorys: '',
          dataFiltering: [],
          dataItemFiltering: []
        }],
        kind: 1,
        isUpdateRegularly: false,
        styleConfig: '',
        isOrder: false,
        sortType: '',
        updateRegularlyType: '1小时',
        ringModuleData: [ // 环形进度图选择数据
          { progress: '', target: '', moduleName: '', themeColor: '#406EFF' }
        ]
      },
      defaultLayout: { x: 0, y: 0, h: 0 },
      formRules: { name: [{ required: true, trigger: 'blur', message: '请填写模块名称' }] },
      defaultData: null
    };
  },
  computed: {
    fieldList() {
      if (!this.dataForm.tags) return [];
      return this.dataForm.tags.map(i => ({ name: i.tagName }));
    },
    isChart() {
      return this.dataForm.moduleType === TAG_MODULE_STYLE.HISTOGRAM_MODULE || this.dataForm.moduleType === TAG_MODULE_STYLE.PIE_MODULE;
    }
  },
  mounted() {
    if (this.$refs.chartStyleRef) {
      this.$refs.chartStyleRef.getData();
    }
    if (this.$refs.SelectLabel) {
      this.dataForm.tags = this.$refs.SelectLabel.getLabelData();
    }
    this.defaultData = JSON.parse(JSON.stringify(this.dataForm));
  },
  methods: {
    setDefault(data) {
      const dataForm = this.dataForm;
      const layout = parseJson(data.layout);
      Object.assign(dataForm, data);
      dataForm.layoutNum = Number(layout.w || 12);
      this.defaultLayout = layout;
      if (this.$refs.chartStyleRef && dataForm.id) {
        this.$refs.chartStyleRef.setStyleDefault(dataForm.styleConfig);
      }
      // 圆环进度图编辑状态获取的tag不重新生成uuid
      this.$refs.SelectLabel.setDefault(data.tags, !this.isEdit);
      this.$forceUpdate();
    },
    isDataChange() {
      if (this.$refs.chartStyleRef) {
        this.$refs.chartStyleRef.getData();
      }
      if (this.$refs.SelectLabel) {
        this.dataForm.tags = this.$refs.SelectLabel.getLabelData();
      }
      return JSON.stringify(this.dataForm) !== JSON.stringify(this.defaultData);
    },
    toSubmit() {
      const chartStyleRef = this.$refs.chartStyleRef;
      const moduleNameFormRef = this.$refs.moduleNameForm;
      const dataForm = chartStyleRef.getData();
      const tags = this.$refs.SelectLabel.getLabelData();

      if (!dataForm.isOrder) {
        dataForm.sortFieldName = '';
        dataForm.sortType = '';
        dataForm.showNums = '';
      }
      dataForm.tags = tags;
      const validatePromise = [];
      validatePromise.push(chartStyleRef.validate());
      validatePromise.push(this.$refs.SelectLabel.validate());
      if (moduleNameFormRef) validatePromise.push(moduleNameFormRef.validate());
      Promise.all(validatePromise).then(res => {
        // 判断标签有无选取字段
        let tagsFieldIdEmpty = true;
        const set = new Set();
        let isRepeatNames = false;
        tags.forEach(i => {
          if ((i.fieldName && i.fieldName !== '') || i.tagType === 1) {
            tagsFieldIdEmpty = false;
          }
          if (set.has(i.tagName)) { isRepeatNames = true; } else { set.add(i.tagName); }
        });
        if (tagsFieldIdEmpty) {
          this.$message.error('请选择标签字段');
          return;
        }
        if (isRepeatNames) {
          this.$message.error('标签名称重复');
          return;
        }
        const layout = this.defaultLayout;
        layout.w = dataForm.layoutNum;
        this.defaultLayout = layout;
        dataForm.layout = JSON.stringify(layout);
        dataForm.tabId = this.tabId;
        dataForm.isMobile = this.$route.query.editMobileMode ? 1 : 0;
        this.setDefaultYearOnYear(dataForm);
        if (!this.isEdit || this.editType === 'copy') {
          this.add(dataForm);
        } else {
          this.edit(dataForm);
        }
      }).catch((err) => {
        console.log(err);
        this.$message.warning('请检查信息是否填写完整');
      });
    },
    add(dataForm) {
      this.btnLoading = true;
      createChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('新增成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    edit(dataForm) {
      this.btnLoading = true;
      dataForm.id = this.$route.params.id || '';
      editChartTable(dataForm).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
        // this.$message.error(err.message);
      });
    },
    handleClose() {
      this.$emit('goBack');
    },
    // 环形进度图
    getTagNames() {
      const tags = this.$refs.SelectLabel.getLabelData() || [];
      this.$set(this.dataForm, 'tags', tags);
    },
    tabNameChange(val) {
      this.getTagNames();
      !val && this.resetRingModuleData();
    },
    tagDelete() {
      this.getTagNames();
      this.resetRingModuleData();
    },
    resetRingModuleData() {
      this.dataForm.ringModuleData && this.dataForm.ringModuleData.forEach(item => {
        const progressIndex = this.dataForm.tags.findIndex(curTag => curTag.uuid === item.progress);
        progressIndex === -1 && (item.progress = '');
        const targetIndex = this.dataForm.tags.findIndex(curTag => curTag.uuid === item.target);
        targetIndex === -1 && (item.target = '');
      });
    },
    setDefaultYearOnYear(params) {
      if (params.tags && params.tags.length) {
        params.tags.forEach(i => {
          if (i.dataItemFiltering && i.dataItemFiltering.length) {
            i.dataItemFiltering.forEach(j => {
              const isTime = this.isTimeField(j);
              const isOpenFilter = j.isOpenFilter && !j.timeRangeType && j.defaultMath;
              const openMonthOnMonth = isOpenFilter || j.timeRangeType; // 是否开启了同比环比
              if (!isTime || !openMonthOnMonth) {
                j.monthOnMonth = false;
                j.yearOnYear = false;
                j.timeRangeType = '';
              }
              if (isTime && j.begin && j.end && j.operation === '') {
                j.operation = '=';
              }
              if (i.editTarget) {
                j.monthOnMonth = false;
                j.yearOnYear = false;
              }
            });
          }
          if (i.dataFiltering && i.dataFiltering.length) {
            i.dataFiltering.forEach(j => {
              if (!j.timeRangeType || j.timeRangeType === '' || j.type !== 0) {
                j.monthOnMonth = false;
                j.yearOnYear = false;
                j.timeRangeType = '';
              }
              if (i.editTarget) {
                j.monthOnMonth = false;
                j.yearOnYear = false;
              }
            });
          }
        });
      }
    },
    isTimeField(item) {
      // 字段的字段类型 optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
      const optionsType = item.optionsType;
      // 如果 optionsType 存在则使用新逻辑，不存在则使用旧逻辑
      if (optionsType || optionsType === 0) {
        return optionsType === 1;
      }
      return item.field.indexOf('日期') >= 0 || item.field.indexOf('时间') >= 0 || item.field === '预计到款';
    },
    switchProcess({ id }) {
      this.$emit('switchProcess', { id });
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px !important;
    }
  }
}
.select-updateRegularlyType {
  width: 120px;
  margin-left: 10px;
  &::v-deep {
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.select-sort {
  display: flex;
  &::v-deep {
    .el-input {
      width: 120px !important;
      margin-left: 10px;
    }
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.foot-info {
  display: flex;
  align-items: center;
  position: absolute;
  right: 10px;
  .item {
    flex-shrink: 0;
    margin-left: 10px;
    color: #999;
  }
}
</style>
